/* Copyright Homeaway, Inc 2005-2008. All Rights Reserved.
 * No unauthorized use of this software.
 */
package org.mis6323.data.dao.impl;

import java.util.List;
import org.mis6323.data.dao.ProviderDao;
import org.mis6323.data.model.Provider;

/**
 * tvu has not yet bothered to enter a useful javadoc comment.
 */
public class FileBasedProviderDaoImpl extends AbstractFileBasedDaoImpl<Provider> implements ProviderDao{


    // map a name to a provider for efficient lookup
    private Long currentId;

    public FileBasedProviderDaoImpl(String fileName) {
        super(fileName);

        // Go through the set of provider loaded to find the largest id
        currentId = 0l;
        for(Provider p : this.data) {
            currentId = Math.max(currentId, p.getId());
        }
    }
    @Override
    public void createProvider(Provider provider) {
        // since we want to look up provider by full name
        // enforce that it's unique
        if (this.searchProviderByFullName(provider.getFullName()) != null) {
            throw new IllegalArgumentException("Full name is already used");
        }
        // increment current id by 1 so that new provider has a unique id
        this.currentId += 1;
        provider.setId(this.currentId);
        this.data.add(provider);

        // immediately flush the content of the data to disc.
        this.flush();
    }

    @Override
    public void deleteProvider(Long providerId) {
        Provider p = this.searchProviderById(providerId);
        if (p != null) {
            this.data.remove(p.getId());
        }
        this.flush();
    }
    
    @Override
    public void updateProvider(Provider provider) {
        // if the full name from provider object looked up using id is <> from
        // the passed in phone # and the passed in # already exist
        Provider old = this.searchProviderById(provider.getId());
        if (old == null) {
            throw new IllegalArgumentException("Provided is not saved");
        }
        if (!old.getFullName().equals(provider.getFullName()) &&
                this.searchProviderByFullName(provider.getPhoneNo()) != null) {
            throw new IllegalArgumentException("Full name is already used");
        }

//        this.data.add(provider);
        this.flush();
    }

    @Override
    public Provider searchProviderById(Long providerId) {
        for (Provider p : this.data) {
            if (p.getId() == providerId) {
                return p;
            }
        }
        return null;
    }

    @Override
    public Provider searchProviderByFullName(String fullName) {
        for (Provider p : this.data) {
            if (p.getFullName().equals(fullName)) {
                return p;
            }
        }
        return null;
    }

    @Override
    public List<Provider> getAllProviders() {
        return this.data;
    }

}
